import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Album {
  final int userId;
  final int id;
  final String title;

  const Album({
    required this.userId,
    required this.id,
    required this.title
  });

  factory Album.fromJson(Map<String, dynamic> json) {
    return switch(json) {
      { 'userId': int userId, 'id': int id, 'title': String title } => Album(
        userId: userId,
        id: id,
        title: title,
      ),
      _ => throw const FormatException('Fail to load Album'),
    };
  }
}

Future<Album> fetchAlbum() async {
  final response = await http.get(
    Uri.parse('https://jsonplaceholder.typicode.com/albums/2')
  );

  if (200 == response.statusCode) {
    return Album.fromJson(jsonDecode(response.body) as Map<String, dynamic>);
  } else {
    throw Exception("Fail to Load Album");
  }
}

class HttpWidget extends StatefulWidget {
  const HttpWidget({ super.key });

  @override
  State<HttpWidget> createState() => _HttpWidget();
}

class _HttpWidget extends State<HttpWidget> {
  late Future<Album> futureAlbum;

  @override
  void initState() {
    super.initState();
    futureAlbum = fetchAlbum();
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("HttpWidget"),
        centerTitle: true,
      ),
      body: Center(
        child: FutureBuilder(
          future: futureAlbum,
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              return Text(snapshot.data!.title);
            } else if (snapshot.hasError) {
              return Text('${ snapshot.error }');
            }
            return const CircularProgressIndicator();
          }
        )
      ),
    );
  }
}